﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mitek.Models.Auth;
using Mitek.Services.Auth;
using Mitek.Web.App_Start;
using Mitek.Web.ViewModels;
using Mitek.Web.Filters;

namespace Mitek.Web.Controllers
{
    public class UserController : BaseController
    {
        private readonly IUserService _userService;
       
        public UserController(IUserService userService)
        {
           this._userService = userService;
        }

        #region 用户登陆
        // GET: User/Login
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(UserLoginViewModel vm)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var re = _userService.UserLogin(vm.UserName, vm.Password);
                    if (re == null)
                        return Json(new { Result = "error", msg = "登录失败用户名或密码不正确，请稍后重试..." });

                    var user = EmitMapper.ObjectMapperManager.DefaultInstance.GetMapper<Mitek.Models.Auth.User, ViewModels.ApplicationUser>().Map(re);

                    SessionContext.SignIn(user);
                    
                    return Json(new { Result = "success", Url = "/report/create", msg = "登录成功，页面正在跳转，请稍等..." });

                }
                else
                {
                    if (Request.IsAjaxRequest())
                        return Json(new { Result = "error" });
                    else
                        return View(vm);
                }
            }
            catch (Exception ex)
            {
                if (Request.IsAjaxRequest())
                    return Json(new { Result = "error", msg = ex.Message });
                else
                    return View(vm);
            }
        }
        #endregion

        #region 用户注册
        // GET: User/Register
        public ActionResult Register()
        {
            //该类数据均从数据库中读取
            //ViewBag.province = new ApiController().SetOptionItem(new ApiController().GetProvince(),null);
            //ViewBag.city = new ApiController().SetOptionItem(new List<CityDetails>(),null);
            //ViewBag.hospital = new ApiController().SetOptionItem(new List<Hospital>(),null);
            return View();
        }
        [HttpPost]
        public ActionResult Register(UserRegisterViewModel vm)
        {
            try
            {
                //判断验证码是否正确
                if (vm.VerifyCode != Session["RegitCode"].ToString())
                    return Json(new { Result = "error", msg = "验证码不正确，请仔细核对！" });

                //判断数据库中是否已存在此用户
                var re = _userService.GetUserByMobile(vm.Mobile);
                if (re != null)
                {
                    return Json(new { Result = "error", msg = "注册失败,该手机号已存在!" });
                }

                //判断用户名是否合法
                if (ModelState.IsValid)
                {
                    User user = new User
                    {
                        Name = vm.Name,
                        UserName = vm.Mobile,
                        PassWord = Utils.Security.Encrypt.Md5Encrypt(vm.Mobile.Substring(vm.Mobile.Length-6,6)),///默认为手机号后六位
                        RoleID = (int.Parse(vm.RoleID) == (int)Mitek.Web.Helpers.Role.医生 ? (int)Mitek.Web.Helpers.Role.助手 : int.Parse(vm.RoleID)),
                        Mobile = vm.Mobile,
                        CreatedTime = DateTime.Now,
                        ModifiedTime = DateTime.Now,
                        Province = vm.Province,
                        City = vm.City,
                        Hospital = vm.Hospital,
                        Deparment = vm.Deparment,
                        DoctorOffice = vm.DoctorOffice,
                        DoctorCertificate = vm.DoctorCertificate,
                        //Domain=vm.Deparment,
                        Status = 0, //若角色为医生，则需要后台审核后通过,角色为患者无需审核。
                        IsDeleted = false
                     };
                    _userService.AddUser(user);

                    ///更改Operation表中UserID信息
                    //var _case = _mycaseservice.getCaseByMobile(vm.Mobile);
                    //if (_case != null)
                    //{
                    //    var _operation = _operationservice.getOperation(_case.OperationID);
                    //    _operation.UserID = user.ID;
                    //    _operationservice.UpdateOperation(_operation);
                    //}

                    return Json(new { Result = "success", Url = Url.Action("Login", "User"), msg = "注册成功，请登录..." });
                }
                return Json(new { Result = "error", msg = "注册失败!" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "error", msg = ex.Message });
            }
        }
 
        #endregion

        #region 注销
        public ActionResult Logout()
        {
            SessionContext.SignOut();
            return RedirectToAction("Login", "User");
        }
        #endregion

        #region 修改用户信息
        public ActionResult Information()
        {
            if (SessionContext.CurrentUser == null)
            {
                return RedirectToAction("Login", "User");
            }
            else
            {
                var re = _userService.GetUserByID(SessionContext.CurrentUser.ID);
                //ViewBag.province = _cityDetailservice.GetByID(re.Province).Name;
                //ViewBag.city = _cityDetailservice.GetByID(re.City).Name;
                //ViewBag.hospital = _cityDetailservice.GetHospitalByID(re.Hospital).Name;
                return View(re);
            }
        }
        [HttpPost]
        public ActionResult Information(FormCollection collection)
        {
            try
            {
                var re = _userService.GetUserByID(SessionContext.CurrentUser.ID);
                if (re.PassWord != Utils.Security.Encrypt.Md5Encrypt(collection["oldpassword"]))
                {
                    return Json(new { Result = "error", msg = "原始密码错误!" });
                }
                else
                {
                    re.PassWord = Utils.Security.Encrypt.Md5Encrypt(collection["PassWord"]);
                    _userService.UpdateUser(re);
                    return Json(new { Result = "success", Url = Url.Action("index", "doccenter"), msg = "修改成功！" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { Result = "error", msg = ex.Message });
            }
          
        }
        #endregion

        #region 用户中心
        public ActionResult UserCenter()
        {
            if (SessionContext.CurrentUser == null)
            {
                return RedirectToAction("Login", "User");
            }
            else
            {
                var reurl = "";
                switch (SessionContext.CurrentUser.Role)
                {
                    case (int)Mitek.Web.Helpers.Role.医院:
                        reurl = "/hoscenter/index/";
                        break;
                    case (int)Mitek.Web.Helpers.Role.医生:
                        reurl = "/doccenter/index/";
                        break;
                    case (int)Mitek.Web.Helpers.Role.助手:
                        reurl = "/assistcenter/index/";
                        break;
                    case (int)Mitek.Web.Helpers.Role.患者:
                        reurl = "/patcenter/index/";
                        break;
                }
                return Redirect(reurl);
            }
        }
        #endregion

    }

}